package servlet.client;

import dao.domain.Book;
import dao.domain.Client;
import service.BookService;
import service.ClientService;
import service.UserService;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

/**
 * @author gzb
 * @Date 2023/10/16
 * @Description ${PACKAGE_name}
 */
@WebServlet(name = "ClientSellServlet", value = "/ClientSellServlet")
public class ClientSellServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int number = Integer.parseInt(request.getParameter("number"));
        String account = UserService.getAccountFromCookie(request);
        String msg = "{\"msg\":\"fall\"}";
        try {
            Client client = (Client) UserService.selectByAccount("client", account);
            Book book = BookService.selectById(number);
            boolean flag = ClientService.purchase(client, book);
            if (flag) {
                msg = "{\"msg\":\"success\"}";
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        response.getWriter().write(msg);
        System.out.println("finish");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("ClientSellServlet现在来了一个post请求，将要去走get的代码了。");
        doGet(request, response);
    }
}
